package server;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Vector;

/**
 * this class handles user's receive message
 * @author kaidix
 *
 */
public class sendMessage implements Runnable{

	private ObjectOutputStream out;
	private String name;
	private database.MyIMDB db;
	private boolean stop = false;
	 Socket socket;
	 /**
	  * check if user have unread message and send it
	  * @param s the socket to send
	  * @param name the user's name
	  * @param db the database's reference
	  */
	public sendMessage(Socket s,String name,database.MyIMDB db){
		try {
			socket = s;
			this.out=new ObjectOutputStream(socket.getOutputStream());
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		this.name=name;
		this.db=db;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(!stop){
			Vector<database.message> a = db.getMessage(name);
			Vector<database.message> b = db.getGroupMessage(name);
			if(a.size()!=0){
				for(int i = 0 ;i < a.size();i++){
					try {
						sendMessage1(a.elementAt(i).name,a.elementAt(i).message);
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				db.removeMessages(name);
			}
			
			if(b.size()!=0){
				for(int i = 0 ;i < b.size();i++){
					try {
						sendMessage2(b.elementAt(i).name,b.elementAt(i).message);
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				db.removeGroupMessages(name);
			}
			
			
			
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * send the one to one chatting message
	 * @param from the sender
	 * @param mess the text
	 * @throws IOException
	 */
	private void sendMessage1(String from, String mess) throws IOException{
		data.TextMsg msg = new data.TextMsg(from,"",mess);
		data.Message m = new data.Message(data.Information.MESSAGE_TYPE_SENT_TO,msg);
		out.writeObject(m);
		out.flush();
	}
	/**
	 * send the group message
	 * @param from the group name
	 * @param mess the text
	 * @throws IOException
	 */
	private void sendMessage2(String from, String mess) throws IOException{
		data.TextMsg msg = new data.TextMsg(from,"",mess);
		data.Message m = new data.Message(data.Information.MESSAGE_TYPE_GROUP_SENT,msg);
		out.writeObject(m);
		out.flush();
	}
	/**
	 * stop this thread
	 */
	public void stop(){
		stop = true;
	}
}
